﻿#region Header

/*
Behavioral Rating of Dancing Human Crowds based on Motion Patterns
By

Pascal Hauser 
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

and

Raphael Gfeller
Dipl. Ing. in Informatik, Hochschule für Technik Rapperswil, 2006
Master Thesis, Hochschule für Technik Rapperswil, 2008-2010

*/

#endregion

#region Usings

using System;
using System.Drawing;
using System.Globalization;
using System.Runtime.InteropServices;
using System.Windows;
using System.Windows.Data;
using System.Windows.Interop;
using System.Windows.Media.Imaging;
using Emgu.CV;

#endregion

namespace paravili.Ui {
	/// <summary>
	/// Description of the class
	/// </summary>
	[ValueConversion(typeof(IImage), typeof(BitmapSource))]
	public class ImageToBitmapSourceConverter : IValueConverter {
		#region Public Properties

		// public Properties located here

		#endregion

		#region Public Methods

		// public methods located here

		#endregion

		#region Private Methods

		// private methods located here

		#endregion

		#region Private Fields

		// private fields located here

		#endregion

		#region IValueConverter Members

		public object Convert(object value, Type targetType, object parameter, CultureInfo culture) {
			var val = value as IImage;
			return ToBitmapSource(val);
		}

		public object ConvertBack(object value, Type targetType, object parameter, CultureInfo culture) {
			throw new NotImplementedException();
		}

		#endregion

		/// <summary>
		/// Delete a GDI object
		/// </summary>
		/// <param name="o">The poniter to the GDI object to be deleted</param>
		/// <returns></returns>
		[DllImport("gdi32")]
		private static extern int DeleteObject(IntPtr o);

		/// <summary>
		/// Convert an IImage to a WPF BitmapSource. The result can be used in the Set Property of Image.Source
		/// </summary>
		/// <param name="image">The Emgu CV Image</param>
		/// <returns>The equivalent BitmapSource</returns>
		public static BitmapSource ToBitmapSource(IImage image) {
			using (Bitmap source = image.Bitmap) {
				IntPtr ptr = source.GetHbitmap(); //obtain the Hbitmap

				BitmapSource bs = Imaging.CreateBitmapSourceFromHBitmap(ptr, IntPtr.Zero, Int32Rect.Empty,
																		 BitmapSizeOptions.FromEmptyOptions());

				DeleteObject(ptr); //release the HBitmap
				return bs;
			}
		}
	}
}